#include <QDebug>
#include "QNBExCamera.h"

#ifdef _WINXP

QNBExCamera::QNBExCamera(int width, int height, QObject *parent) :
                            QObject(parent),
                            width_(width),
                            height_(height)
{
     capture_.mWidth = width;
     capture_.mHeight = height;
     capture_.mTargetBuf = new int[width * height];

     int devices = setupESCAPI();
     if (devices == 0)
     {
         qDebug() << "[Camera] ESCAPI initialization failure or no devices found";
     }
}

QNBExCamera::~QNBExCamera()
{
    if(capture_.mTargetBuf != NULL) {
        delete [] capture_.mTargetBuf;
        capture_.mTargetBuf = NULL;
    }

    deinitCapture(0);
}

int QNBExCamera::initialize()
{
    if (initCapture(0, &capture_) == 0)
    {
        qDebug() << "[Camera] Capture failed - device may already be in use";
        return -2;
    }
    return 0;
}

void QNBExCamera::deinitialize()
{
    if(capture_.mTargetBuf != NULL) {
        delete [] capture_.mTargetBuf;
        capture_.mTargetBuf = NULL;
    }

    deinitCapture(0);
}

int QNBExCamera::capture(CAPTURE_TYPE type)
{

    m_frameMutex.lock();
    doCapture(0);
    while(isCaptureDone(0) == 0);

    image_ = QImage(width_, height_, QImage::Format_RGB888);
    for(int y(0); y < height_; ++y)
    {
        for(int x(0); x < width_; ++x)
        {
            int index(y * width_ + x);
            image_.setPixel(x, y, capture_.mTargetBuf[index]);
         }
    }
    m_frameMutex.unlock();

    if(type == CAPTURED_FOR_VIDEO) {
       image2_ = QImage(image_);
    }
    else {
       emit Captured(image_);
    }

    return 1;
}
#else
QNBExCamera::QNBExCamera(int width, int height, QObject *parent)
{

}

QNBExCamera::~QNBExCamera()
{

}

#endif



